<?php

namespace app\controllers;

use app\common\services\ShortMessageServices;
use app\common\services\StaticServices;
use app\controllers\common\BaseController;
use app\models\Member;
use app\models\MemberFlow;
use app\models\SpiderContent;
use Yii;
use yii\base\Exception;
use yii\web\Response;

class MemberController extends BaseController
{
  public $short_msg = null;

  public function __construct($id, $module, array $config = [])
  {
    parent::__construct($id, $module, $config);
    $this->short_msg = new ShortMessageServices();
  }

  public function actionLogin()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $member_name = trim(Yii::$app->request->post('member_name', ''));
        $member_pwd = trim(Yii::$app->request->post('member_pwd'));

        if (mb_strlen($member_name, 'utf-8') < 1) {
          throw new Exception('请填写账号');
        }
        if (mb_strlen($member_pwd, 'utf-8') < 1) {
          throw new Exception('请填写密码');
        }
        $member_info = Member::find()->where(['member_name' => $member_name])->one();
        if (!$member_info) {
          throw new Exception('没有此用户', -1);
        }
        if ($member_info->member_pwd != md5($member_pwd)) {
          throw new Exception('请填写正确的用户和密码');
        }

        Yii::$app->session->set('member_info', $member_info);
        return ['code' => 200, 'data' => $member_info->member_name, 'msg' => '登录成功', 'session_id' => session_id()];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 用户注册
   * @return array
   */
  public function actionRegister()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $member_name = trim(Yii::$app->request->post('member_name', ''));
        $member_pwd = trim(Yii::$app->request->post('member_pwd', ''));
        $member_email = trim(Yii::$app->request->post('member_email', ''));
        $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd', ''));
        $member_company = trim(Yii::$app->request->post('member_company', ''));
        $member_phone = trim(Yii::$app->request->post('member_phone', ''));
        $member_job = trim(Yii::$app->request->post('member_job', ''));
        $code = trim(Yii::$app->request->post('code', ''));
        $member_avatar = trim(Yii::$app->request->post('member_avatar', ''));

        $member_info = Member::find()->where(['member_phone' => $member_phone])->one();
        if ($member_info) {
          throw new Exception('此用户已经存在');
        }
        if (mb_strlen($member_name, 'utf-8') < 1) {
          throw new Exception('请填写用户姓名');
        }
        if ((mb_strlen($member_pwd, 'utf-8') < 1 || mb_strlen($confirm_pwd, 'utf-8') < 1) || $member_pwd != $confirm_pwd) {
          throw new Exception('请输入正确的密码');
        }
        if (filter_var($member_email, FILTER_VALIDATE_EMAIL) == false) {
          throw new Exception('请填写正确的邮箱地址');
        }
        if (mb_strlen($member_company, 'utf-8') < 1) {
          throw new Exception('请填写所属于公司');
        }
        if (!preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $member_phone)) {
          throw new Exception('电话号码不正确');
        }

        $check_code = $this->short_msg->CheckCode($code);
        if ($check_code['code'] != 200) {
          throw new Exception($check_code['msg']);
        }

        $member = new Member();
        $member->member_name = $member_name;
        $member->member_email = $member_email;
        $member->member_pwd = md5($member_pwd);
        $member->member_company = $member_company;
        $member->member_job = isset($member_job) ? $member_job : '';
        $member->member_phone = $member_phone;
        $member->member_avtar = isset($member_avatar) ? $member_avatar : '';
        $member->update_time = time();
        $member->create_time = time();
        $member->save(0);

        $this->short_msg->UseCode($code);
        Yii::$app->session->set('member_info', $member);
        return ['code' => 200, 'msg' => '注册成功'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  public function actionGetValidateCode()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $phone = trim(Yii::$app->request->get('phone', ''));
        if (!preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $phone)) {
          throw new Exception('电话号码有误');
        }
        $template = '亲爱的用户，您好！您的注册验证码为{code}，有效期为5分钟，如非本人操作，请忽略此短信。';

        StaticServices::getCode(mt_rand(100000, 999999), $template, $phone);
        return ['code' => 200, 'msg' => '发送成功'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  public function actionGetForgetCode()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $phone = trim(Yii::$app->request->get('phone', ''));
        if (!preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $phone)) {
          throw new Exception('电话号码有误');
        }
        $template = '亲爱的用户，您好！您的设置新密码的验证码为{code}，有效期为5分钟，如非本人操作，请忽略此短信。';

        StaticServices::getCode(mt_rand(100000, 999999), $template, $phone);
        return ['code' => 200, 'msg' => '发送成功'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 设置新密码
   * @return array
   * @throws \Throwable
   */
  public function actionForgetPwd()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $member_phone = trim(Yii::$app->request->post('member_phone'));
        $new_pwd = trim(Yii::$app->request->post('new_pwd', ''));
        $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd', ''));
        $code = trim(Yii::$app->request->post('code', ''));

        $check_code = $this->short_msg->CheckCode($code);
        if ($check_code['code'] != 200) {
          throw new Exception('验证码错误');
        }
        $this->short_msg->UseCode($code);

        if (!$member_phone || !$new_pwd || !$confirm_pwd) {
          throw new Exception('参数有误');
        }
        if ($new_pwd != $confirm_pwd) {
          throw new Exception('请填写正确的密码');
        }
        $member_info = Member::find()->where(['member_phone' => $member_phone])->one();
        if ($member_info) {
          $member_info->member_pwd = md5($new_pwd);
          $member_info->update_time = time();
          $member_info->update(0);

          return ['code' => 200, 'msg' => '修改成功'];
        }
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 验证用户是否存在
   * @return array
   */
  public function actionCheckMember()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $session_member = Yii::$app->session->get('member_info');
        if (!isset($session_member->id)) {
          throw new Exception('请先登录');
        }

        return ['code' => 200, 'data' => $session_member->member_name];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 用户收藏资讯
   * @return array
   * @throws \Throwable
   */
  public function actionCollect()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $spider_id = intval(Yii::$app->request->post('id', 0));
        $spider_info = SpiderContent::find()->where(['id' => $spider_id])->one();
        if (!$spider_info) {
          throw new Exception('参数有误');
        }
        $member_info = Yii::$app->session->get('member_info');
        if (!isset($member_info->id)) {
          throw new Exception('请先登录');
        }
        $member_flow = MemberFlow::find()->where(['member_id' => $member_info->id, 'conent_id' => $spider_id])->one();
        if ($member_flow) {
          //取消用户收藏
          MemberFlow::deleteAll(['id' => $member_flow->id]);
          if ($spider_info->flow_count > 0) {
            $spider_info->flow_count -= 1;
          } else {
            $spider_info->flow_count = 0;
          }
          $spider_info->update(0);
          return ['code' => 200, 'msg' => '取消收藏'];
        } else {
          $flow_info = new MemberFlow();
          $flow_info->member_id = $member_info->id;
          $flow_info->conent_id = $spider_id;
          $flow_info->create_time = time();
          if ($flow_info->save(0)) {
            //更新资讯信息
            $spider_info->flow_count += 1;
            $spider_info->update(0);
            return ['code' => 200, 'msg' => '收藏好了'];
          }
        }
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 用户收藏列表
   * @return array
   */
  public function actionCollectionList()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $p = intval(Yii::$app->request->get('p', 1));
        $session_member = Yii::$app->session->get('member_info');
        if (!isset($session_member->id)) {
          throw new Exception('请先登录');
        }
        $sql = "SELECT `spider_content`.`id`,`spider_content`.`title`,`spider_content`.`cover_img`,`spider_content`.`flow_count`,`spider_content`.`click_count`,`member_flow`.`create_time`
                FROM `member_flow` LEFT JOIN `spider_content` ON `spider_content`.`id`=`member_flow`.`conent_id` WHERE `member_flow`.`member_id`={$session_member->id}";
        $collection = SpiderContent::findBySql($sql);

        $page_size = 5;
        $collection_count = $collection->count();
        $total_page = ceil($collection_count / $page_size);
        $offset = ($p - 1) * $page_size;

        $sql1 = "SELECT `spider_content`.`id`,`spider_content`.`title`,`spider_content`.`cover_img`,`spider_content`.`flow_count`,`spider_content`.`click_count`,`member_flow`.`create_time`,`spider_content`.`source`
                FROM `member_flow` LEFT JOIN `spider_content` ON `spider_content`.`id`=`member_flow`.`conent_id` WHERE `member_flow`.`member_id`={$session_member->id} LIMIT {$offset},{$page_size}";

        $collection_info = SpiderContent::findBySql($sql1)->all();

        $data = ['collection_count' => $collection_count, 'collection_info' => $collection_info, 'total_page' => $total_page];
        return ['code' => 200, 'data' => $data];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 获取用户足迹列表
   * @return array
   */
  public function actionFootprint()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $p = intval(Yii::$app->request->get('p', 1));
        $session_member = Yii::$app->session->get('member_info');
        if (!isset($session_member->id)) {
          throw new Exception('请先登录');
        }
        $flow_ids = [];
        if (isset($session_member->id)) {
          //获取用户收藏信息
          $member_flow_info = MemberFlow::find()->select(['id', 'conent_id'])->where(['member_id' => $session_member->id])->asArray()->all();
          foreach ($member_flow_info as $item) {
            array_push($flow_ids, $item['conent_id']);
          }
        }
        $sql = "SELECT `spider_content`.`title`,`spider_content`.`cover_img`,`spider_content`.`source`,`spider_content`.`flow_count`,`spider_content`.`click_count`,`member_footprint`.`create_time`,`spider_content`.`id`
                FROM `member_footprint` LEFT JOIN `spider_content` ON `member_footprint`.`spider_id`=`spider_content`.`id` WHERE `member_footprint`.`member_id`={$session_member->id}";
        $footprint_info = SpiderContent::findBySql($sql);
        $page_size = 5;
        $footprint_count = $footprint_info->count();
        $total_page = ceil($footprint_count / $page_size);
        $offset = ($p - 1) * $page_size;
        $sql1 = "SELECT `spider_content`.`title`,`spider_content`.`cover_img`,`spider_content`.`source`,`spider_content`.`flow_count`,`spider_content`.`click_count`,`member_footprint`.`create_time`,`spider_content`.`id`
                FROM `member_footprint` LEFT JOIN `spider_content` ON `member_footprint`.`spider_id`=`spider_content`.`id` WHERE `member_footprint`.`member_id`={$session_member->id} LIMIT {$offset},{$page_size}";

        $list = SpiderContent::findBySql($sql1)->asArray()->all();
        if (count($flow_ids) == 0) {
          foreach ($list as $key => $item) {
            $list[$key]['is_flow'] = false;
          }
        } else {
          foreach ($list as $key => $item) {
            if (in_array($item['id'], $flow_ids)) {
              $list[$key]['is_flow'] = true;
            } else {
              $list[$key]['is_flow'] = false;
            }
          }
        }
        $data = ['count' => $footprint_count, 'info' => $list, 'total_page' => $total_page];
        return ['code' => 200, 'data' => $data];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 用户收藏信息
   *
   * @return void
   */
  public function actionMemberFlow()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $session_member = Yii::$app->session->get('member_info');

        if (!$session_member) {
          throw new Exception('数据有误');
        }
        $flow_ids = [];
        //获取用户收藏信息
        $member_flow_info = MemberFlow::find()->select(['id', 'content_id'])->where(['member_id' => $session_member->id])->all();
        foreach ($member_flow_info as $item) {
          array_push($flow_ids, $item['content_id']);
        }
        return ['code' => 200, 'data' => $flow_ids];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  /**
   * 用户收藏信息
   *
   * @return void
   */
  public function actionFlow()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $session_member = Yii::$app->session->get('member_info');
        $spider_id = intval(Yii::$app->request->post('id', 0));
        if (!isset($session_member->id)) {
          throw new Exception('请先登录');
        }

        $spider_info = SpiderContent::find()->where(['id' => $spider_id])->one();
        if (!$spider_info) {
          throw new Exception('数据有误');
        }
        // 查看此信息用户是否收藏过
        $member_flow = MemberFlow::find()->where(['member_id' => $session_member->id, 'conent_id' => $spider_id])->one();
        if ($member_flow) {
          throw new Exception('已经收藏过了');
        }
        $flow_info = new MemberFlow();
        $flow_info->member_id = $session_member->id;
        $flow_info->conent_id = $spider_id;
        $flow_info->create_time = time();
        $flow_info->save(0);

        return ['code' => 200, 'msg' => '收藏成功'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  public function actionLogout()
  {
    if (Yii::$app->request->isGet) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        Yii::$app->session->remove('member_info');
        return ['code' => 200, 'msg' => '退出登录'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }
}
